import string
import random

from django.contrib.auth import get_user_model,login,logout
from django.core.mail import send_mail
from django.shortcuts import render
import logging
from django.http.response import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods

from zlauth.models import CaptchaModel
from django.shortcuts import render, redirect, reverse
from .forms import RegisterForm,LoginForm

# Create your views here.

## 登录视图函数
@require_http_methods(["GET","POST"])
def zllogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        print("POST 请求 进行数据校验==============1")
        formLogin = LoginForm(request.POST)
        if formLogin.is_valid():
            email = formLogin.cleaned_data.get('email')
            password = formLogin.cleaned_data.get('password')
            remember = formLogin.cleaned_data.get('remember')
            ## 根据 email 查库 .first() 更安全 不会抛出异常
            User = get_user_model()
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                ## 登录 调用 框架中的 login
                login(request, user)
                ## is remember me ?
                if not remember:
                    request.session.set_expiry(0)
                return redirect('/')
            else:
                ## 查无此人
                formLogin.add_error("email","邮箱或者密码错误")
                return render(request, 'login.html',context={'form': formLogin})
                #return redirect(reverse('zlauth:login'))

## 退出登录
def zllogout(request):
    logout(request)
    return redirect('/')

## 注册视图函数
@require_http_methods(["GET","POST"])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        # POST 请求 进行数据校验
        postResult = RegisterForm(request.POST)  # 创建表单实例
        if postResult.is_valid():
                # 获取清理后的表单数据
                email = postResult.cleaned_data.get('email')
                username = postResult.cleaned_data.get('username')
                password = postResult.cleaned_data.get('password')

                # 使用 Django 内置的 User 模型创建用户
                User = get_user_model()  # 获取自定义的用户模型（如果有的话）
                User.objects.create_user(username=username, email=email, password=password)

                # 注册成功后，重定向到登录页面
                return redirect(reverse('zlauth:login'))

        else:
            # 如果表单验证失败，记录错误并返回表单
            print(f"注册失败，表单错误：{postResult.errors}")  # 使用 f-string 格式化错误信息
            return render(request, 'register.html', {"form": postResult})



##  发送邮件
def send_email_captchart(request):
    ## ?eamil=xxxx
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code":"400","message":"必须传递邮箱"})
    ## 生成验证码
    captchart = "".join(random.sample(string.digits,6))
    ## 验证码有则创建 无则更新
    CaptchaModel.objects.update_or_create(email=email,defaults={"captcha":captchart})
    send_mail("知了验证码",message=f"你的验证码是：{captchart}",from_email=None,recipient_list=[email])
    return JsonResponse({"code":"200","message":"验证码发送成功"})

